package com.smbpics

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class FileAdapter(
    private val smbClient: SmbClient,
    private val onItemClick: (SmbImageFile) -> Unit
) : ListAdapter<SmbImageFile, FileAdapter.FileViewHolder>(DiffCallback()) {

    private lateinit var imageLoader: ImageLoader

    class FileViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivIcon: ImageView = view.findViewById(R.id.ivIcon)
        val tvFileName: TextView = view.findViewById(R.id.tvFileName)
        val tvFileInfo: TextView = view.findViewById(R.id.tvFileInfo)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.file_item, parent, false)
        if (!::imageLoader.isInitialized) {
            imageLoader = ImageLoader(parent.context)
        }
        return FileViewHolder(view)
    }

    override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
        val file = getItem(position)
        holder.tvFileName.text = file.name
        holder.tvFileInfo.text = formatFileInfo(file)

        // Set click listener
        holder.itemView.setOnClickListener {
            onItemClick(file)
        }

        // Load thumbnail for images, set folder icon for directories
        if (file.isDirectory) {
            holder.ivIcon.setImageResource(R.drawable.ic_folder)
        } else {
            // Load image thumbnail using enhanced image loader
            CoroutineScope(Dispatchers.IO).launch {
                val imageData = smbClient.downloadImage(file.path)
                imageData?.let { data ->
                    imageLoader.loadImage(data, holder.ivIcon, file.name)
                } ?: run {
                    CoroutineScope(Dispatchers.Main).launch {
                        holder.ivIcon.setImageResource(R.drawable.ic_image)
                    }
                }
            }
        }

        // Set focus handling for TV navigation
        holder.itemView.isFocusable = true
        holder.itemView.isFocusableInTouchMode = true
    }

    private fun formatFileInfo(file: SmbImageFile): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val date = Date(file.lastModified)
        val size = formatFileSize(file.size)
        return "$size | ${dateFormat.format(date)}"
    }

    private fun formatFileSize(bytes: Long): String {
        return when {
            bytes < 1024 -> "$bytes B"
            bytes < 1024 * 1024 -> "${bytes / 1024} KB"
            bytes < 1024 * 1024 * 1024 -> "${bytes / (1024 * 1024)} MB"
            else -> "${bytes / (1024 * 1024 * 1024)} GB"
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<SmbImageFile>() {
        override fun areItemsTheSame(oldItem: SmbImageFile, newItem: SmbImageFile): Boolean {
            return oldItem.path == newItem.path
        }

        override fun areContentsTheSame(oldItem: SmbImageFile, newItem: SmbImageFile): Boolean {
            return oldItem == newItem
        }
    }
}